const getUploadService = require('../../modules/loopback-core/services/aws-s3-service');
const path = require('path')
const atob = require('atob');

module.exports = (req, res, container, name, cb) => {
  getUploadService(req).then((uploadService) => {
    if (!uploadService) {
      cb(new Error('File system has wrong configurations.'));
      return;
    }
    if (process.env.AWS_S3_IS_USED === 'true') {
      uploadService.download(req, res, container, name, (error, data) => {
        if (error) {
          if (error.code === 'ENOENT') {
            error.status = 404;
          } else {
            error.status = 501;
          }
          cb(error);
          return;
        }
  
        let originalFilename = '';
        if (data.Metadata && data.Metadata['original-filename']) {
          originalFilename = `attachment; filename=${
              data.Metadata['original-filename']
          }`;
        }
        console.log(`download  filename:${data.Metadata['original-filename']} filename1:${originalFilename}`);
        cb(null, data.Body, data.ContentType, originalFilename);
      });
    } else {
      let data = req.query;
      let filePath = path.join('media',data.container,data.name)
      res.download(filePath); 
    }
  }).catch((err) => {
    cb(err);
  });
};

